package com.example.makerspace.aop;
import com.alibaba.fastjson.JSON;
import com.example.makerspace.domain.BmsLog;
import com.example.makerspace.service.BmsLogService;
import com.example.makerspace.utils.IpUtils;
import com.example.makerspace.utils.JwtUtils;
import com.jthinking.common.util.ip.IPInfo;
import com.jthinking.common.util.ip.IPInfoUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;


/**
 * @author pangxie
 * @data 2020/11/15 15:54
 *
 * 切面注解
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);





    @Autowired
    BmsLogService bmsLogService;


    @Pointcut("@annotation(com.example.makerspace.aop.Log)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object object=new Object();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        long beginTime = System.currentTimeMillis();
        // 执行方法
        try {
              object = point.proceed();
              saveLog(point, beginTime);
        }
        catch (Exception e){
            BmsLog sysLog = new BmsLog();
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            Log syslog = method.getAnnotation(Log.class);
            if (syslog != null) {
                // 注解上的描述
                sysLog.setOperationType(syslog.value());
            }
            String ipAddr = IpUtils.getIpAddr(request);
            IPInfo ipInfo = IPInfoUtils.getIpInfo(ipAddr);
            sysLog.setMapAddress(ipInfo.getAddress());
            String username = JwtUtils.getUsername(request);
            sysLog.setRole(username);
            sysLog.setMethod(request.getMethod());
            String path = request.getRequestURI();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
            sysLog.setBasePath(basePath);
            sysLog.setTime(System.currentTimeMillis() - beginTime);
            sysLog.setStatus("失败");
            Map<String, String[]> paramMap = request.getParameterMap();
            if (paramMap != null) {
                String params = JSON.toJSONString(paramMap);
                params = params.substring(0, params.length() < 1000 ? params.length() : 999);
                sysLog.setParameter(params);
            }
            sysLog.setErrorMsg(e.getMessage());
            bmsLogService.insert(sysLog);
        }

        return object;
    }

    void saveLog(ProceedingJoinPoint joinPoint, long beginTime) throws InterruptedException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                Method method = signature.getMethod();
                BmsLog sysLog = new BmsLog();
                Log syslog = method.getAnnotation(Log.class);
                if (syslog != null) {
                    // 注解上的描述
                    sysLog.setOperationType(syslog.value());
                }
                // 获取request
                String username = JwtUtils.getUsername(request);

                // 设置地址
                String ipAddr = IpUtils.getIpAddr(request);
                IPInfo ipInfo = IPInfoUtils.getIpInfo(ipAddr);
                sysLog.setMapAddress(ipInfo.getAddress());
                sysLog.setRole(username);
                // 设置根路径

                String path = request.getRequestURI();
                String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
                sysLog.setBasePath(basePath);
                sysLog.setMethod(request.getMethod());
                // 获取用户设备信息
                // sysLog.setUserAgent(request.getHeader("User-Agent"));
                // 用户名
                //请求的参数
                Map<String, String[]> paramMap = request.getParameterMap();
                if (paramMap != null) {
                    String params = JSON.toJSONString(paramMap);
                    params = params.substring(0, params.length() < 1000 ? params.length() : 999);
                    sysLog.setParameter(params);
                }
                sysLog.setTime(System.currentTimeMillis()-beginTime);
                sysLog.setStatus("成功");
                // 保存系统日志
                bmsLogService.insert(sysLog);
        }


}

